from django.shortcuts import render, redirect
from app01.models import UserInfo


def register(request):
    if request.method == "GET":
        return render(request, 'auth.html', {"action": "注册"})
    else:
        username = request.POST.get("username")
        password = request.POST.get("password")
        # 先查数据库中是否有了用户输入的用户名
        user_obj = UserInfo.objects.filter(user=username).first()
        # 如果查到了，表示该用户已注册，给前端返回消息，说用户已注册
        if user_obj:
            return render(request, 'auth.html', {"msg": f"您输入的用户名[{username}]已经注册了，请重新输入!!", "action": "注册"})
        else:  # 否则，直接写入到数据库
            UserInfo.objects.create(user=username, pwd=password)
            return redirect('/login/')


def login(request):
    if request.method == "GET":
        return render(request, 'auth.html', {"action": "登录"})
    else:
        username = request.POST.get("username")
        password = request.POST.get("password")
        # 根据用户输入的用户名和密码去数据库中进行校验，如果校验通过，说明登录成功，可以跳转到主页
        user_obj = UserInfo.objects.filter(user=username, pwd=password).first()
        # 如果查到了，表示该用户已注册，给前端返回消息，说用户已注册
        if user_obj:
            request.session['user'] = user_obj.user
            request.session['is_login'] = True
            return redirect('/index/')
        else:  # 否则，给前端返回消息，说用户或者密码错误
            return render(request, 'auth.html', {"msg": f"用户名或者密码错误，请重新输入!!", "action": "登录"})


def logout(request):
    request.session.clear()
    return redirect('/login/')


def index(request):
    user = request.session.get('user', '游客')
    return render(request, 'base.html', {"user": user, "action": 'index'})


def pay(request):
    user = request.session.get('user', '游客')
    return render(request, 'base.html', {"user": user, "action": 'pay'})
